package com.weacar.activity;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.example.zhouwei.library.CustomPopWindow;
import com.google.gson.Gson;
import com.weacar.R;
import com.weacar.bean.BaseBean;
import com.weacar.bean.LoginBean;
import com.weacar.config.Constans;
import com.weacar.fragment.AuctionFragment;
import com.weacar.fragment.HomeFragment;
import com.weacar.fragment.MineFragment;
import com.weacar.fragment.MyPriceFragment;
import com.weacar.utils.AppManager;
import com.weacar.utils.DesUtil;
import com.weacar.utils.NetWorkUtil;
import com.weacar.utils.SharedPreferenceUtil;
import com.weacar.utils.SystemUtil;
import com.weacar.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.lzh.framework.updatepluginlib.UpdateBuilder;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {
    // 退出时间
    private long mExitTime;
    @BindView(R.id.rg_group)
    RadioGroup rg_group;
    @BindView(R.id.cl_main)
    ConstraintLayout cl_main;
    public Fragment[] mFragments;
    // 点击下标
    private int mIndex;
    public LoginBean loginBean;

    // 点击事件
    @OnClick({R.id.rb_home, R.id.rb_big_house, R.id.rb_my_price, R.id.rb_mine})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rb_home:
                setIndexSelected(0);
                // initNotice();
                setStatusBarStyle("1");
                break;
            case R.id.rb_big_house:
                setStatusBarStyle("1");
                setIndexSelected(1);
                break;
            case R.id.rb_my_price:
                setStatusBarStyle("1");
                setIndexSelected(2);
                break;
            case R.id.rb_mine:
                setStatusBarStyle("2");
                setIndexSelected(3);
                break;
        }
    }

    /**
     * 显示我的出价页面
     */
    public void showMyPriceFragment() {
        rg_group.check(R.id.rb_my_price);
        setStatusBarStyle("1");
        setIndexSelected(2);
        MyPriceFragment myPriceFragments = (MyPriceFragment) mFragments[2];
        HomeFragment homeFragment = (HomeFragment) mFragments[0];
        homeFragment.getRecommend();
        myPriceFragments.refresh = true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AppManager.getInstance().addActivity(this);
        ButterKnife.bind(this);
        rg_group.check(R.id.rb_home);
        setStatusBarStyle("1");
        initFragments();
        loginBean = SharedPreferenceUtil.getObject(getApplicationContext(), "loginBean");
        checkUpdate();
        updateUserInfo();
        boolean b = getIntent().getBooleanExtra("jumpMyPrice", false);
        if (b) {
            showMyPriceFragment();
        }

//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                initNotice();
//            }
//        }, 500);
    }

    /**
     * 检测app是否需要更新
     */
    public void checkUpdate() {
        UpdateBuilder.create().check();
    }

    /**
     * 获取用户信息
     */
    public void updateUserInfo() {

        if (loginBean == null) {
            return;
        }

        if (!NetWorkUtil.isNetworkAvailable(this)) {
            ToastUtil.showShort(getApplicationContext(), "当前网络不可用");
            return;
        }

        RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.get_userinfo);
        params.setCacheMaxAge(0);
        JSONObject js_request = new JSONObject();
        try {
            js_request.put("token", loginBean.getMsg().getToken());
            params.setAsJsonContent(true);
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));

            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    closeLoading();
                    LogUtils.d("update_result = " + result);
                    Gson gson = new Gson();
                    BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                    if (baseBean != null && baseBean.getCode() == 1) {
                        try {
                            LoginBean loginBean = gson.fromJson(DesUtil.decrypt(baseBean.getData()), LoginBean.class);
                            LogUtils.d(loginBean.toString());
                            if (loginBean != null) {
                                SharedPreferenceUtil.setObject(getApplicationContext(), "loginBean", loginBean);
                                Constans.isRefreshPersonInfo = true;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        // 错误信息提示
                        if (baseBean != null) {
                            try {
                                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(DesUtil.decrypt(baseBean.getData()));
                                String msg = jsonObject.get("msg").toString();
                                if (msg != null && msg.equals("token已失效")) {
                                    SharedPreferenceUtil.setObject(getApplicationContext(), "loginBean", null);
                                    Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                                    startActivity(intent);
                                    finish();
                                }

                                ToastUtil.showShort(getApplicationContext(), msg);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastUtil.showShort(getApplicationContext(), "系统异常");
                        }
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    closeLoading();
                }

                @Override
                public void onCancelled(CancelledException cex) {
                    closeLoading();
                }

                @Override
                public void onFinished() {
                    closeLoading();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    // 通知初始化
    public void initNotice() {

        Resources resources = getApplication().getResources();

        DisplayMetrics displayMetrics = resources.getDisplayMetrics();

        int widthPixels = (int) (displayMetrics.widthPixels * 0.8);//当前屏幕宽

        int heightPixels = (int) (displayMetrics.heightPixels * 0.65);//当前屏幕高


        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_notice, null);
        TextView tv_close = contentView.findViewById(R.id.tv_close);


        final CustomPopWindow customPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .size(widthPixels, heightPixels)//显示大小
                .create()
                .showAtLocation(cl_main, Gravity.CENTER, 0, 0);

        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customPopWindow.dissmiss();
            }
        });
    }


    // 初始化fragment
    private void initFragments() {
        HomeFragment homeFragment = new HomeFragment();
        AuctionFragment auctionFragment = new AuctionFragment();
        MyPriceFragment myPriceFragment = new MyPriceFragment();
        MineFragment mineFragment = new MineFragment();
        mFragments = new Fragment[]{homeFragment, auctionFragment, myPriceFragment, mineFragment};
        FragmentTransaction ft =
                getSupportFragmentManager().beginTransaction();
        ft.add(R.id.fl_content, homeFragment).commit();
        setIndexSelected(0);
    }

    // 设置显示指定的fragment
    public void setIndexSelected(int index) {
        if (mIndex == index) {
            return;
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        //隐藏
        ft.hide(mFragments[mIndex]);
        //判断是否添加
        if (!mFragments[index].isAdded()) {
            ft.add(R.id.fl_content, mFragments[index]).show(mFragments[index]);
        } else {
            ft.show(mFragments[index]);
        }
        // 异步防止频繁操作崩溃
        fragmentManager.executePendingTransactions();
        ft.commit();
        //再次赋值
        mIndex = index;
    }


    // APP退出管理
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    ToastUtil.showShort(getApplicationContext(), "再按一次退出程序");
                    mExitTime = System.currentTimeMillis();
                } else {
                    AppManager.getInstance().exitApp();
                    finish();
                }
                break;
            default:
                return super.onKeyDown(keyCode, event);
        }
        return true;
    }
}
